package com.hectopascal.excel.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.converters.longconverter.LongStringConverter;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.hectopascal.excel.listener.ExcelPropertyNotNullListener;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class EasyExcelUtils {
    //默认情况，即没有特殊sheetName和dataStartRowIndex
    @SneakyThrows
    public static <T> List<T> read(MultipartFile file, Class<T> clazz) {
        return read(file, clazz, "Sheet1", 1);
    }

    //MultipartFile类型
    //读取Excel文件并映射到对象中
    @SneakyThrows
    public static <T> List<T> read(MultipartFile file, Class<T> clazz, String sheetName, Integer dataStartRowIndex) {
        return EasyExcel.read(file.getInputStream(), clazz, null)
                //工作表名称
                .sheet(sheetName)
                //从第x行开始读取
                .headRowNumber(dataStartRowIndex)
                .registerReadListener(new ExcelPropertyNotNullListener())
                .doReadSync();
    }

    //默认类型
    @SneakyThrows
    public static <T> List<T> read(File file, Class<T> clazz) {
        return read(file, clazz, "Sheet1", 1);
    }

    //File类型
    @SneakyThrows
    public static <T> List<T> read(File file, Class<T> clazz, String sheetName, Integer dataStartRowIndex){
        return EasyExcel.read(file, clazz, null)
                .sheet(sheetName)
                .headRowNumber(dataStartRowIndex)
                .registerReadListener(new ExcelPropertyNotNullListener())
                .doReadSync();
    }

    //导出Excel文件
    //head:model类,data:数据
    @SneakyThrows
    public static <T> void write(HttpServletResponse response, String filename, String sheetName, Class<T> head, List<T> data) {
        EasyExcel.write(response.getOutputStream(), head)
                //交给Servlet自己处理关闭流程
                .autoCloseStream(Boolean.FALSE)
                //基于column长度
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                //避免Long类型丢失精度
                .registerConverter(new LongStringConverter())
                .sheet(sheetName)
                .doWrite(data);
        //设置header与contentType,避免报错时，响应contentType已经被修改
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
    }
}
